refactoring for cppcheck "The scope of the variable can be reduced" (#677)
authortsteven4 <13596209+tsteven4@users.noreply.github.com>
Mon, 1 Feb 2021 18:40:49 +0000 (11:40 -0700)
committerGitHub <noreply@github.com>
Mon, 1 Feb 2021 18:40:49 +0000 (11:40 -0700)
* refactoring for cppcheck "The scope of the variable can be reduced"

The c++17 "If Statement with Initializer" often are useful in resovling
these.

* more scope reduction.

* and another.

17 files changed:
csv_util.cc
duplicate.cc
garmin.cc
gui/filterdata.cc
gui/mainwindow.cc
igc.cc
jeeps/gpsapp.cc
jeeps/gpsusbcommon.cc
jeeps/gpsusbwin.cc
lowranceusr.cc
magproto.cc
mapasia.cc
mmo.cc
position.cc
skytraq.cc
tpg.cc
wbt-200.cc

index 770e3c80d4df1b41f91f35540e0fa67bb3f51b4b..4743bfe63058ac6068aaaac507dc0c3a6557236c 100644 (file)
@@ -62,7 +62,6 @@ csv_stringtrim(const char* string, const char* enclosure, int strip_max)
   static const char* p1 = nullptr;
   char* tmp = xstrdup(string);
   size_t elen;
-  int stripped = 0;
 
   if (!strlen(string)) {
     return (tmp);
@@ -92,6 +91,7 @@ csv_stringtrim(const char* string, const char* enclosure, int strip_max)
 
   /* if we have enclosures, skip past them in pairs */
   if (elen) {
+    int stripped = 0;
     while (
       (stripped < strip_max) &&
       ((size_t)(p2 - p1 + 1) >= (elen * 2)) &&
index 27fe896fc5e3a101d52c45ba718358857771a99b..7d0cd83043e0cdb0d5afe99773db92dffe7b77d4 100644 (file)
@@ -140,9 +140,9 @@ int DuplicateFilter::compare(const void* a, const void* b)
 
 void DuplicateFilter::process()
 {
-  btree_node* newnode, * btmp, * sup_tree = nullptr;
+  btree_node* btmp = nullptr;
+  btree_node* sup_tree = nullptr;
   btree_node* oldnode = nullptr;
-  unsigned long crc = 0;
   struct {
     char shortname[32];
     char lat[13];
@@ -186,9 +186,9 @@ void DuplicateFilter::process()
 
     }
 
-    crc = get_crc32(&dupe, sizeof(dupe));
+    unsigned long crc = get_crc32(&dupe, sizeof(dupe));
 
-    newnode = (btree_node*)xcalloc(sizeof(btree_node), 1);
+    auto* newnode = (btree_node*)xcalloc(sizeof(btree_node), 1);
     newnode->data = crc;
     newnode->wpt = waypointp;
 
index a58a2bfa33a9622723f833820b54d88570efc80b..871626e6841aa79b5800feb9e8aef5485ee09ae6 100644 (file)
--- a/garmin.cc
+++ b/garmin.cc
@@ -369,9 +369,8 @@ rw_deinit()
 static int
 waypt_read_cb(int total_ct, GPS_PWay* )
 {
-  static int i;
-
   if (global_opts.verbose_status) {
+    static int i;
     i++;
     waypt_status_disp(total_ct, i);
   }
@@ -872,10 +871,10 @@ sane_GPS_Way_New()
 static int
 waypt_write_cb(GPS_PWay*)
 {
-  static int i;
   int n = waypt_count();
 
   if (global_opts.verbose_status) {
+    static int i;
     i++;
     waypt_status_disp(n, i);
   }
@@ -1028,11 +1027,9 @@ waypoint_prepare()
 static void
 waypoint_write()
 {
-  int32 ret;
-
   int n = waypoint_prepare();
 
-  if ((ret = GPS_Command_Send_Waypoint(portname, tx_waylist, n, waypt_write_cb)) < 0) {
+  if (int32 ret = GPS_Command_Send_Waypoint(portname, tx_waylist, n, waypt_write_cb); ret < 0) {
     fatal(MYNAME ":communication error sending waypoints..\n");
   }
 
index 6fc304f14c10da3d22e1b1f4e6a6a308f47ac09a..59f40b14f0b0680bc13333f400d4cfa152a4944f 100644 (file)
@@ -79,7 +79,6 @@ static QString optionDate(const QDateTime& dt, bool useLocal)
 //------------------------------------------------------------------------
 QStringList TrackFilterData::makeOptionString()
 {
-  static const char* fixStrings[] = {"none", "pps", "dgpss", "3d", "2d"}; // match with designer!
   QStringList args;
   if (!inUse_) {
     return args;
@@ -87,6 +86,7 @@ QStringList TrackFilterData::makeOptionString()
 
   QString s;
   if (GPSFixes) {
+    static const char* fixStrings[] = {"none", "pps", "dgpss", "3d", "2d"}; // match with designer!
     s += QString(",fix=%1").arg(fixStrings[GPSFixesVal]);
   }
   if (course) {
@@ -201,7 +201,7 @@ QStringList MiscFltFilterData::makeOptionString()
       "rte=wpt",
       "wpt=rte",
       "rte=trk",
-      "trk=wpt",
+      "trk=wpt"
     };
     args << QString("-x");
     QString s= QString("transform,%1").arg(xformStr[transformVal_]);
index 931a9fcba357e77a705bef17c3416c411721a1d1..915d75e2aa9fd6b4c62e22d7a07bc10deef93b7c 100644 (file)
@@ -917,10 +917,9 @@ bool MainWindow::runGpsbabel(const QStringList& args, QString& errorString,
 
   waitDlg->show();
   waitDlg->exec();
-  int exitCode = -1;
   bool retStatus = false;
   if (waitDlg->getExitedNormally()) {
-    exitCode = waitDlg->getExitCode();
+    int exitCode = waitDlg->getExitCode();
     if (exitCode == 0) {
       retStatus = true;
     } else  {
diff --git a/igc.cc b/igc.cc
index fd860c3e48a08798a0f7d3497a42478a1022c64a..950fdf5a3ef0d06c6035aec32a9f20f0af4249d2 100644 (file)
--- a/igc.cc
+++ b/igc.cc
@@ -167,13 +167,11 @@ inline state_t operator++(state_t& s, int) // postfix
  */
 static void igc_task_rec(const char* rec)
 {
-  static char flight_date[7];
   static unsigned int num_tp, tp_ct;
   static route_head* rte_head;
   static time_t creation;
 
   char task_num[5];
-  char task_desc[MAXRECLEN];
   unsigned int lat_deg, lat_min, lat_frac;
   unsigned int lon_deg, lon_min, lon_frac;
   char lat_hemi[2], lon_hemi[2];
@@ -184,6 +182,8 @@ static void igc_task_rec(const char* rec)
 
   // First task record identifies the task to follow
   if (id == state) {
+    static char flight_date[7];
+    char task_desc[MAXRECLEN];
     task_desc[0] = '\0';
     if (sscanf(rec, "C%2u%2u%2u%2u%2u%2u%6[0-9]%4c%2u%78[^\r]\r\n",
                &tm.tm_mday, &tm.tm_mon, &tm.tm_year,
@@ -596,7 +596,6 @@ static void wr_header()
   time_t date;
   static const char dflt_str[] = "Unknown";
   const char* str = nullptr;
-  Waypoint* wpt;
 
   get_tracks(&pres_track, &track);
   if (!track && pres_track) {
@@ -624,7 +623,7 @@ static void wr_header()
 // FIXME: This almost certainly introduces a memory leak because str
 // is a c string that's used for totally too many things.  Just let it
 // leak for now. 2013-12-31 robertl
-    if (nullptr != (wpt = find_waypt_by_name("PILOT")) && !wpt->description.isEmpty()) {
+    if (const Waypoint* wpt = find_waypt_by_name("PILOT"); (nullptr != wpt) && !wpt->description.isEmpty()) {
       xfree(str);
       str = xstrdup(CSTRc(wpt->description));
     } else {
index 3e66604f5abf5fc7d88191f28a1fc7bed1644abd..c66f28a151cb50d297c4ac5191857bd04485d6eb 100644 (file)
@@ -385,19 +385,14 @@ carry_on:
 ************************************************************************/
 static void GPS_A001(GPS_PPacket& packet)
 {
-  int32 entries;
-  int32 i;
-  UC* p;
-  US tag;
-  US data;
   US lasta=0;
 
-  entries = packet.n / 3;
-  p = packet.data;
+  int32 entries = packet.n / 3;
+  UC* p = packet.data;
 
-  for (i=0; i<entries; ++i,p+=3) {
-    tag = *p;
-    data = GPS_Util_Get_Short(p+1);
+  for (int32 i=0; i<entries; ++i,p+=3) {
+    US tag = *p;
+    US data = GPS_Util_Get_Short(p+1);
 
     switch (tag) {
       /* Only one type of P[hysical] so far */
@@ -7557,8 +7552,6 @@ static UC Is_Trackpoint_Invalid(GPS_PTrack trk)
 ************************************************************************/
 void GPS_Prepare_Track_For_Device(GPS_PTrack** trk, int32* n)
 {
-  int32 i, j;
-
   /* D303/304 marks track segments with two consecutive invalid track
    * points instead of the tnew flag. Create them unless we're at the
    * beginning of a track or there are already invalid track points
@@ -7566,12 +7559,12 @@ void GPS_Prepare_Track_For_Device(GPS_PTrack** trk, int32* n)
    * done here because it will change the number of track points.
    */
   if (gps_trk_type == pD303 || gps_trk_type == pD304) {
-    for (i=0; i<*n; ++i) {
+    for (int32 i=0; i<*n; ++i) {
       if ((*trk)[i]->tnew && i>0 && !(*trk)[i]->ishdr && !(*trk)[i-1]->ishdr) {
         /* Create invalid points based on the data from the point
          * marked with tnew and the one before it.
          */
-        for (j=i-1; j<=i; j++) {
+        for (int32 j=i-1; j<=i; ++j) {
           if (!Is_Trackpoint_Invalid((*trk)[j])) {
             GPS_PTrack trkpt = GPS_Track_New();
             *trkpt = *((*trk)[j]);
index 548c54885f69033f7e347bfbc1896d7a606a08ee..b935e6cd428dc34e67b6fc7e4b71ae7be9a3dedb 100644 (file)
@@ -153,28 +153,26 @@ top:
 int
 gusb_cmd_send(const garmin_usb_packet* opkt, size_t sz)
 {
-  unsigned int rv, i;
-
   auto* obuf = (unsigned char*) &opkt->dbuf;
-  const char* m1, *m2;
+  const char* m2;
 
-  rv = gusb_llops->llop_send(opkt, sz);
+  unsigned int rv = gusb_llops->llop_send(opkt, sz);
 
   if (gps_show_bytes) {
     const unsigned short pkttype = le_read16(&opkt->gusb_pkt.databuf[0]);
     const unsigned short pkt_id = le_read16(&opkt->gusb_pkt.pkt_id);
     GPS_Diag("TX [%zu]:", sz);
 
-    for (i=0; i<sz; i++) {
+    for (unsigned int i=0; i<sz; ++i) {
       GPS_Diag("%02x ", obuf[i]);
     }
 
-    for (i=0; i<sz; i++) {
+    for (unsigned int i=0; i<sz; ++i) {
       int c = obuf[i];
       GPS_Diag("%c", isascii(c) && isalnum(c) ? c : '.');
     }
 
-    m1 = Get_Pkt_Type(pkt_id, pkttype, &m2);
+    const char* m1 = Get_Pkt_Type(pkt_id, pkttype, &m2);
 
     GPS_Diag("(%-8s%s)\n", m1, m2 ? m2 : "");
   }
index d3767aa62e8259322998fd562819fdfba28a501f..975663c3e0c70cec00a4236f9f409775797a8fcd 100644 (file)
@@ -193,10 +193,10 @@ static char** get_garmin_mountpoints(void)
   char* p = szTemp;
   char** dlist = (char **) xmalloc(sizeof(*dlist));
 
-  int i = 0;
   dlist[0] = NULL;
 
   if (GetLogicalDriveStringsA(BUFSIZE-1, szTemp)) {
+    int i = 0;
     while (*p) {
       dlist = (char **) xrealloc(dlist, sizeof(*dlist) * (++i + 1));
       //            fprintf(stderr, "Found: %d, %s\n", i, p);
index 50d07784b771985f4cc5834074a3555df8c63870..a4244d51ab25fac5640474b713407d0d62b6cc84 100644 (file)
@@ -1832,7 +1832,6 @@ void
 LowranceusrFormat::write()
 {
   QString buf;
-  int len;
 
   setshort_length(mkshort_handle, 15);
 
@@ -1867,7 +1866,7 @@ LowranceusrFormat::write()
     gbfputint32(DataStreamVersion, file_out);
 
     /* file title */
-    if ((len = strlen(opt_title)) == 0) {
+    if (int len = strlen(opt_title); len == 0) {
       buf = QString("GPSBabel generated USR data file");
     } else {
       if (len > MAXUSRSTRINGSIZE) {
@@ -1897,7 +1896,7 @@ LowranceusrFormat::write()
     gbfputint32(opt_serialnum_i, file_out);
 
     /* content description */
-    if ((len = strlen(opt_content_descr)) == 0) {
+    if (int len = strlen(opt_content_descr); len == 0) {
       buf = QString("Waypoints, routes, and trails");
     } else {
       if (len > MAXUSRSTRINGSIZE) {
index 38e3265941b234fd2498055162ecbda9bbc904dc..bbd84d53908a595c69fea38d2ae5f5537d2febe2 100644 (file)
@@ -1037,7 +1037,6 @@ mag_rteparse(char* rtemsg)
   char xbuf[100],next_stop[100],abuf[100];
   char* currtemsg;
   static mag_rte_head_t* mag_rte_head;
-  char* p;
 
 #if 0
   sscanf(rtemsg,"$PMGNRTE,%d,%d,%c,%d%n",
@@ -1089,7 +1088,7 @@ mag_rteparse(char* rtemsg)
     }
 
     /* trim CRC from waypoint icon string */
-    if ((p = strchr(abuf, '*')) != nullptr) {
+    if (char* p = strchr(abuf, '*'); p != nullptr) {
       *p = '\0';
     }
 
@@ -1469,7 +1468,6 @@ mag_route_trl(const route_head* rte)
   QScopedPointer<char, QScopedPointerPodDeleter> obuff;
   QString buff1;
   QString buff2;
-  QString* pbuff;
   QString icon_token;
 
   /* count waypoints for this route */
@@ -1491,6 +1489,7 @@ mag_route_trl(const route_head* rte)
       icon_token = mag_find_token_from_descr(waypointp->icon_descr);
     }
 
+    QString* pbuff;
     if (i == 1) {
       pbuff = &buff1;
     } else {
index 53a4af5de062c534ff99350fc01d77568b4794e8..baaa5b718fb6788aaec6f65e32e16db579782d71 100644 (file)
@@ -210,13 +210,13 @@ static void
 tr7_disp_waypt_cb(const Waypoint* wpt)
 {
   unsigned char buff[TR7_S_SIZE];
-  double speed, course;
 
   memset(buff, 0, sizeof(buff));
 
   le_write32(&buff[TR7_S_LON], (int)(wpt->longitude * 1000000.0));
   le_write32(&buff[TR7_S_LAT], (int)(wpt->latitude * 1000000.0));
 
+  double course;
   if WAYPT_HAS(wpt, course) {
     course = wpt->course;
   } else if (wpt_tmp != nullptr) {
@@ -241,6 +241,7 @@ tr7_disp_waypt_cb(const Waypoint* wpt)
     buff[TR7_S_MIN] = t.minute();
     buff[TR7_S_SEC] = t.second();
 
+    double speed;
     if WAYPT_HAS(wpt, speed) {
       speed = wpt->speed;
     } else if (wpt_tmp != nullptr) {
diff --git a/mmo.cc b/mmo.cc
index 74d3fa3f3011c1ae90ba4c051c1859017c8f849e..9e91e16a170ec22fcb6682d66919282d631c75ca 100644 (file)
--- a/mmo.cc
+++ b/mmo.cc
@@ -331,13 +331,14 @@ static mmo_data_t* mmo_read_object();
 static void
 mmo_end_of_route(mmo_data_t* data)
 {
-#ifdef MMO_DBG
-  const char* sobj = "CObjRoute";
-#endif
   auto* rte = (route_head*) data->data;
-  char buf[7];
 
   if (mmo_version >= 0x12) {
+#ifdef MMO_DBG
+    const char* sobj = "CObjRoute";
+#endif
+    char buf[7];
+
     mmo_fillbuf(buf, 7, 1);
     DBG((sobj, "route data (since 0x12): "));
 #ifdef MMO_DBG
index 6c1b86e1ed53baefc56f787fed7a861573d565ef..f0200631760475f1395aa742b08f5e951ad462d3 100644 (file)
@@ -52,9 +52,9 @@ void PositionFilter::position_runqueue(WaypointList* waypt_list, int qtype)
   int nelems = qlist.size();
 
   for (int i = 0 ; i < nelems ; ++i) {
-    bool something_deleted = false;
-
     if (!qlist.at(i).deleted) {
+      bool something_deleted = false;
+
       for (int j = i + 1 ; j < nelems ; ++j) {
         if (!qlist.at(j).deleted) {
           double dist = gc_distance(qlist.at(j).wpt->latitude,
index 20811648dd6f72310877771a8643705ace6fad26..06be955caae67d62c7a2c02791d8860724216d03 100644 (file)
@@ -1209,7 +1209,6 @@ skytraq_probe()
     uint8_t odm_ver[4];
     uint8_t revision[4];
   } MSG_SOFTWARE_VERSION;
-  int rc;
 
   // TODO: get current serial port baud rate and try that first
   // (only sensible if init to 4800 can be disabled...)
@@ -1223,9 +1222,9 @@ skytraq_probe()
     db(1, MYNAME ": Probing SkyTraq Venus at %ibaud...\n", baud_rates[i]);
 
     rd_drain();
-    if ((rc = gbser_set_speed(serial_handle, baud_rates[i])) != gbser_OK) {
+    if (int rc = gbser_set_speed(serial_handle, baud_rates[i]); rc != gbser_OK) {
       db(1, MYNAME ": Set baud rate to %d failed (%d), retrying...\n", baud_rates[i], rc);
-      if ((rc = gbser_set_speed(serial_handle, baud_rates[i])) != gbser_OK) {
+      if (int rc = gbser_set_speed(serial_handle, baud_rates[i]); rc != gbser_OK) {
         db(1, MYNAME ": Set baud rate to %d failed (%d)\n", baud_rates[i], rc);
         continue;
       }
@@ -1235,11 +1234,11 @@ skytraq_probe()
 
     skytraq_wr_msg(MSG_QUERY_SOFTWARE_VERSION, /* get firmware version */
                    sizeof(MSG_QUERY_SOFTWARE_VERSION));
-    if ((rc = skytraq_expect_ack(0x02)) != res_OK) {
+    if (int rc = skytraq_expect_ack(0x02); rc != res_OK) {
       db(2, "Didn't receive ACK (%d), retrying...\n", rc);
       skytraq_wr_msg(MSG_QUERY_SOFTWARE_VERSION,       /* get firmware version */
                      sizeof(MSG_QUERY_SOFTWARE_VERSION));
-      if ((rc = skytraq_expect_ack(0x02)) != res_OK) {
+      if (int rc = skytraq_expect_ack(0x02); rc != res_OK) {
         db(2, "Didn't receive ACK (%d)\n", rc);
         continue;
       }
@@ -1250,8 +1249,8 @@ skytraq_probe()
                {
                        continue;
                }*/
-    rc = skytraq_expect_msg(0x80, (uint8_t*)&MSG_SOFTWARE_VERSION, sizeof(MSG_SOFTWARE_VERSION));
-    if (rc < (int)sizeof(MSG_SOFTWARE_VERSION)) {
+    if (int rc = skytraq_expect_msg(0x80, (uint8_t*)&MSG_SOFTWARE_VERSION, sizeof(MSG_SOFTWARE_VERSION));
+        rc < (int)sizeof(MSG_SOFTWARE_VERSION)) {
       db(2, "Didn't receive expected reply (%d)\n", rc);
     } else {
       db(1, MYNAME ": Venus device found: Kernel version = %i.%i.%i, ODM version = %i.%i.%i, "\
@@ -1437,8 +1436,8 @@ ff_vecs_t skytraq_vecs = {
   nullptr,
   &skytraq_args,
   CET_CHARSET_UTF8, 1         /* master process: don't convert anything */
- , NULL_POS_OPS,
- nullptr
 , NULL_POS_OPS,
 nullptr
 };
 
 ff_vecs_t skytraq_fvecs = {
@@ -1457,8 +1456,8 @@ ff_vecs_t skytraq_fvecs = {
   nullptr,
   &skytraq_fargs,
   CET_CHARSET_UTF8, 1         /* master process: don't convert anything */
- , NULL_POS_OPS,
- nullptr
 , NULL_POS_OPS,
 nullptr
 };
 /**************************************************************************/
 /*
diff --git a/tpg.cc b/tpg.cc
index 622b449c45048cb1bcc6ff5a0bb645b780709c88..6e992e9930d9006ae5b191dd3e7e94e593656468 100644 (file)
--- a/tpg.cc
+++ b/tpg.cc
@@ -164,18 +164,11 @@ tpg_waypt_pr(const Waypoint* wpt)
 {
   double lon, lat;
   double amt;
-  char tbuf[64];
   char ocount;
   QString shortname;
   QString description;
   int i;
 
-  /* these unknown 4 are probably point properties (color, icon, etc..) */
-  unsigned char unknown4[] = { 0x78, 0x56, 0x34, 0x12 };
-
-  /* these 2 appear to be constant across test files */
-  unsigned char unknown2[] = { 0x01, 0x80 };
-
   /* our personal waypoint counter */
   waypt_out_count++;
 
@@ -258,7 +251,8 @@ tpg_waypt_pr(const Waypoint* wpt)
   gbfputint16(elev, tpg_file_out);
 
   /* 4 unknown bytes */
-  memset(tbuf, '\0', sizeof(tbuf));
+  /* these unknown 4 are probably point properties (color, icon, etc..) */
+  unsigned char unknown4[] = { 0x78, 0x56, 0x34, 0x12 };
   gbfwrite(unknown4, 1, 4, tpg_file_out);
 
   /* pascal-like description */
@@ -270,6 +264,8 @@ tpg_waypt_pr(const Waypoint* wpt)
     /* last point gets 0x0000 instead of 0x0180 */
     gbfputint16(0, tpg_file_out);
   } else {
+    /* these 2 appear to be constant across test files */
+    unsigned char unknown2[] = { 0x01, 0x80 };
     gbfwrite(unknown2, 1, 2, tpg_file_out);
   }
 }
index 3121eceb77a805f14cba6f0300c636b229758b48..8987b23b0a267a8e4598e0070f9ee272803ffdf6 100644 (file)
@@ -980,7 +980,6 @@ static void file_read()
 {
   char                buf[512];
   struct read_state   st;
-  int                 fmt;
 
   const char*         tk1_magic     = TK1_MAGIC;
   size_t              tk1_magic_len = strlen(tk1_magic) + 1;
@@ -1016,6 +1015,7 @@ static void file_read()
     db(1, "Got bin file\n");
 
     /* Try to guess the data format */
+    int fmt;
     for (fmt = 0; fmt_version[fmt].reclen != 0; fmt++) {
       size_t reclen = fmt_version[fmt].reclen;
       if ((st.data.used % reclen) == 0 && is_valid(&st.data, fmt)) {